/*
 * @Author: Wangjun
 * @Date: 2022-01-12 16:17:40
 * @LastEditTime: 2025-05-16 16:38:16
 * @LastEditors: wangjun haodreams@163.com
 * @Description:日期时间结构体
 * @FilePath: \libs\easy\clock.go
 * hnxr
 */

package easy

import (
	"fmt"
	"time"
)

type Clock struct {
	strTime string //当前时间
	zone    int64  //时区 0~86400
	time    int64  //unix 时间戳
	today   int64  //今天0点的时间
	year    int
	month   int
	day     int
	hour    int
	minute  int
	second  int
	yday    int //一年的第几天
}

/**
 * @description:
 * @param {*} t unix 时间戳, 如果为0, 则使用当前时间
 * @param {int64} offset 时区秒数
 * @return {*}
 */
func NewClock(t, offset int64) *Clock {
	if t == 0 {
		now := time.Now()
		t = now.Unix()
		_, o := now.Zone()
		offset = int64(o)
	}

	m := new(Clock)
	m.zone = offset % 86400
	m.time = t
	m.year, m.month, m.day, m.yday = AbsDate(m.time + offset)
	m.hour, m.minute, m.second = AbsTime(m.time + offset)
	m.strTime = fmt.Sprintf("%d-%02d-%02d %002d:%02d:%02d", m.year, m.month, m.day, m.hour, m.minute, m.second)
	if offset != 0 {
		m.today = FixZoneZeroClock(t, offset)
	}
	return m
}

func NowClock() *Clock {
	now := time.Now()
	_, offset := now.Zone()
	return NewClock(now.Unix(), int64(offset))
}

func NewNowClock() *Clock {
	return NowClock()
}

func (m *Clock) String() string {
	return m.strTime
}

// 年月日
func (m *Clock) YYYYMMDD() int {
	return m.year*1000 + m.month*100 + m.day
}

// 时分秒
func (m *Clock) HHMMSS() int {
	return m.hour*1000 + m.minute*100 + m.second
}

// absWeekday is like Weekday but operates on an absolute time.
func (m *Clock) Weekday() int {
	// January 1 of the absolute year, like January 1 of 2001, was a Monday.
	abs := int64(m.time+m.zone) + secondsPerDay + unixToInternal + internalToAbsolute
	sec := abs % secondsPerWeek
	return int(sec) / secondsPerDay
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Unix() int64 {
	return m.time
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Year() int {
	return m.year
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Month() int {
	return m.month
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Day() int {
	return m.day
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Hour() int {
	return m.hour
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Minute() int {
	return m.minute
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) Second() int {
	return m.second
}

/**
 * @description:
 * @param {*}
 * @return {*}
 */
func (m *Clock) YearDay() int {
	return m.yday
}

/**
 * @description: 今天0点的秒数
 * @param {*}
 * @return {*}
 */
func (m *Clock) Today() int64 {
	return m.today
}

// 今天的秒数
func (m *Clock) TodaySeconds() int64 {
	return m.time - m.today
}
